import Taro from '@tarojs/taro'
import dayjs from 'dayjs'
import { useEffect, useState } from 'react'
import { SwiperItem, View, Swiper, Image, Text, Button } from '@tarojs/components'
import { useRecoilState } from 'recoil'

import Tab from '@/components/Tab'
import NoExploit from '@/components/NoExploit'
import flightState from '@/store/fightStore'
import tools from '@/common/tools'
import { adsReq } from '@/common/api'

import { key } from '../../../../globalConfig'
import './indes.scss'

const DEFAULT_TAB_LIST = [
  {
    label: '单程',
    id: 0
  },
  {
    label: '多程',
    id: 1
  },
  {
    label: '往返',
    id: 2
  }
]

const FLightIndex = () => {
  const [imgList, setImgList] = useState([])
  const [fightInfo, setfightInfo] = useRecoilState(flightState)
  const { departureCityName, destinationCityName, dapartureDate } = fightInfo

  useEffect(() => {
    getAds()
    getLocationInfo()
  }, [])

  const getAds = async () => {
    const res = await adsReq()
    if (res.code === 200) {
      setImgList(res.result)
    }
  }

  const handleTableClick = (id) => {
    console.log(id)
  }

  const handleSearchTickets = () => {
    tools.navigateTo({
      url:'/pages/flight/list/list'
    })
  }

  const handleChooseFlightCity = (type) => {
    setfightInfo({
      ...fightInfo,
      cityType: type
    })

    // 注意需要使用绝对路径
    Taro.navigateTo({
      url: '/pages/airPortList/airPortList'
    })
  }

  const handleChooseDay = () => {
    tools.navigateTo({
      url: '/pages/calendar/calendar'
    })
  }

  /**
   * 得到用户经纬度
   */
  const getLocationInfo = async () => {
    if(tools.isH5()) return
    const response = await Taro.getLocation({
      type: 'gcj02'
    })

    if (response.errMsg !== 'getLocation:ok') {
      tools.showToast('位置获取失败')
    } else {
      getCity(response)
    }
  }

  const getCity = async ({ latitude, longitude }) => {
    const response = await Taro.request({
      url: `https://apis.map.qq.com/ws/geocoder/v1/?key=${key}&location=${latitude},${longitude}`
    })

    if (response.statusCode === 200) {
      const {
        ad_info: { city = '上海', city_code = 2 }
      } = response?.data?.result

      setfightInfo({
        ...fightInfo,
        departureCityName: city,
        departureCityId: city_code
      })
    } else {
      tools.showToast('位置解析失败')
    }
  }

  return (
    <View className='flight-container'>
      <View className='flight-top'>
        <Tab tabList={DEFAULT_TAB_LIST} onTabClick={handleTableClick} className='flight-index-tab'>
          <SwiperItem>
            <View className='item station'>
              <View className='cell from' onClick={() => handleChooseFlightCity('depart')}>
                {departureCityName}
              </View>
              <Text className='iconfont icon-zhihuan' />
              <View className='cell to' onClick={() => handleChooseFlightCity('arrive')}>
                {destinationCityName}
              </View>
            </View>
            <View className='item date' onClick={handleChooseDay}>
              {dayjs(dapartureDate).format('M月D日')}
            </View>
            <Button className='search-btn' onClick={handleSearchTickets}>机票查询</Button>
          </SwiperItem>
          <SwiperItem>
            <NoExploit className='no-data'></NoExploit>
          </SwiperItem>
          <SwiperItem>
            <NoExploit className='no-data'></NoExploit>
          </SwiperItem>
        </Tab>
      </View>
      <Swiper className='advs-banner-bd' autoplay circular interval={3000}>
        {imgList.map(({ id, imgUrl }) => (
          <SwiperItem className='item' key={id}>
            <Image className='img' src={imgUrl}></Image>
          </SwiperItem>
        ))}
      </Swiper>
      {/*  机票底部  */}
      <View className='flight-info' />
    </View>
  )
}

export default FLightIndex
